import hashlib
import os

def md5(a):
    '''
        返回一个字符串的 md5 值，结果为小写
    '''
    if not isinstance(a, bytes):
        a = a.encode("utf-8")
    return hashlib.md5(a).hexdigest()

def timeStamp():
    '''
        获取一个时间戳
    '''
    return str(time.time())

def memToByte(a):
    '''
        将形如 5KB 之类的数据转换为 5120
        要求传入的参数 a 为一个合法的字符串
    '''
    def oneBitTransfer(a):
        a.replace(" ", "")
        if a == "":
            return 0
        if isinstance(a, int):
            return a
        sz = "KMGTPEZY"
        for i in range(len(sz)):
            if sz[i] in a:
                return int(a[:-1]) * 1024 ** (i + 1)
        return int(a)
    if isinstance(a, int):
        return a
    return sum([oneBitTransfer(i) for i in a.split("B")])

def byteToMem(a):
    '''
        将形如 5120 之类的数据转换为 5KB
        传入的参数 a 是一个整数，单位为 Byte
    '''
    ret = []
    sz = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB"]
    cnt = 0
    while a:
        ret += [str(a % 1024) + sz[cnt]]
        cnt += 1
        a //= 1024
    if ret == []:
        ret = ["0B"]
    ret.reverse()
    return " ".join(ret)
        
def memAdd(a, b):
    return byteToMem(memToByte(a) + memToByte(b))

def memSub(a, b):
    return byteToMem(memToByte(a) - memToByte(b))

def memMul(a, b):
    return byteToMem(memToByte(a) * b)

def memLess(a, b):
    return memToByte(a) < memToByte(b)

def memLessOrEqual(a, b):
    return memToByte(a) <= memToByte(b)

def memGreater(a, b):
    return memToByte(a) > memToByte(b)

def memGreaterOrEqual(a, b):
    return memToByte(a) >= memToByte(b)

def memEqual(a, b):
    return memToByte(a) == memToByte(b)
